package com.jinzhi.jzweb.controller.modelConfig;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.domain.modelConfig.DeclareDO;
import com.jinzhi.jzweb.domain.modelConfig.DeclareVo;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.service.modelConfig.DeclareService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;

import javax.servlet.http.HttpServletResponse;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 * 
 * <pre>
 * 申报主体信息表
 * </pre>
 * <small> 2024-01-10 09:37:33 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/declare")
@Api(value = "申报主体信息",tags = "申报主体信息")
public class DeclareController extends BaseController {

	private final DeclareService declareService;

	private final DictService dictService;

	@Autowired
	private OrganizationNewsService organizationNewsService;

	public DeclareController(DeclareService declareService, DictService dictService) {
		this.declareService = declareService;
		this.dictService = dictService;
	}


	@ApiOperation(value = "后台申报列表页面入口", notes = "后台申报列表页面入口")
	@GetMapping()
	@RequiresPermissions("jzweb:declare:declare")
	String Declare(){
	    return "jzweb/declare/declare";
	}


	@ApiOperation(value = "后台申报列表查询接口", notes = "后台申报列表查询接口")
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:declare:declare")
	public Result<List<DeclareDO>> list(DeclareDO declareDTO){
		// 查询列表数据
		EntityWrapper<DeclareDO> wrapper = new EntityWrapper<>();
		if(!StringUtil.isNull(declareDTO.getOrgName())){
			wrapper.like("org_name",declareDTO.getOrgName());
		}
		if(!StringUtil.isNull(declareDTO.getContacts())){
			wrapper.like("contacts",declareDTO.getContacts());
		}
		if(!StringUtil.isNull(declareDTO.getPhone())){
			wrapper.like("phone",declareDTO.getPhone());
		}
		if(!Objects.isNull(declareDTO.getId())){
			wrapper.eq("declare_ready_id",declareDTO.getId());
		}
		if(!Objects.isNull(declareDTO.getCreaterDate())){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			int year = Integer.parseInt(sdf.format(declareDTO.getCreaterDate()));
			wrapper.eq("YEAR(creater_date)",year);
		}
		List<DeclareDO> list = declareService.selectList(wrapper);

		return Result.ok(sortDeclares(list));
	}

	public List<DeclareDO> sortDeclares(List<DeclareDO> declares) {
		return declares.stream()
				.sorted(Comparator
						.comparingInt((DeclareDO declare) -> {
							// 根据 status 的不同返回不同的优先级值
							switch (declare.getStatus()) {
								case 0:  // 待审核
									return 0;
								case 2:  // 审核拒绝
									return 1;
								case 1:  // 审核通过
									return 2;
								default:
									return 3;  // 其他情况
							}
						})
						.thenComparing(Comparator
								// 优先级2：按照createDate降序排序
								.comparing(DeclareDO::getCreaterDate)
								.reversed())
				)
				.collect(Collectors.toList());
	}


	@ApiOperation(value = "压缩包下载验证", notes = "压缩包下载验证")
	@ApiImplicitParams({
	})
	@ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
			@ApiResponse(code = 500, message = "服务器内部异常")})
	@ResponseBody
	@PostMapping(value = "/resourceEfficiency")
	public  Result  resourceEfficiency(@RequestBody DeclareDO declareDTO)  {
		return declareService.declareEfficiency(declareDTO);
	}

	@ApiOperation(value = "压缩包下载", notes = "压缩包下载")
	@ApiImplicitParams({
	})
	@ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
			@ApiResponse(code = 500, message = "服务器内部异常")})
	@ResponseBody
	@GetMapping(value = "/fileDownload")
	public  Result  fileDownload(DeclareDO declareDTO, HttpServletResponse response) throws IOException {
		return declareService.fileDownload(declareDTO,response);
	}


	@ApiOperation(value = "导出申报汇总数据", notes = "导出申报汇总数据")
	@ApiImplicitParams({
	})
	@ApiResponses({@ApiResponse(code = 0, message = "操作成功"),
			@ApiResponse(code = 500, message = "服务器内部异常")})
	@ResponseBody
	@GetMapping(value = "/exportList")
	public  void  exportList(DeclareDO declareDTO, HttpServletResponse response) throws IOException {
		List<DeclareVo> declareVoList = declareService.exportList(declareDTO, response);
		EasyPoiUtil.exportExcel(declareVoList, "申报数据导出", "申报数据导出", DeclareVo.class, "申报数据导出", response);

	}

	/**
	 * 查询所有学校信息返回到前端
	 * @return
	 */
	@GetMapping("/selectSchool")
	@ResponseBody
	@Log("查询学校信息")
	public  Result<?> selectSchool(@RequestParam(required = false,defaultValue = "1")int pageNumber, @RequestParam(required = false,defaultValue = "10")int pageSize, String name){
		Page<Map<Object,Object>> list=organizationNewsService.selectSchool(pageNumber,pageSize,name);
		return Result.ok(list);
	}


	@ApiOperation(value = "新增申报信息",notes = "新增申报信息")
	@ResponseBody
	@PostMapping(value = "/insertDeclare")
	public  Result  insertDeclare(@RequestBody DeclareDO declareDO,@RequestHeader(value = TOKEN_TAG, required = false) String token) {

		//查询磁盘存储路径
		Map<String, String> map =new HashMap<>();
		map.put("type","declare_time");
		map.put("name","declare_time");
		String foundZip = dictService.selDicBy(map);
		if(!StringUtil.notEmpty(token)){
			return Result.fail("token效验失败");
		}
		String dateTimeStr = foundZip;
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
		LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, formatter);
		LocalDateTime now = LocalDateTime.now();
		//超过2025-3-25无法提交
		if(now.isAfter(dateTime) && StringUtil.isNotNull(dateTimeStr)){
			System.out.println("第一个时间较晚");
			return Result.fail("申报入口已关闭");
		}

		//orgName
		//1.根据token获取用户登录数据
		UserDO user = this.getClientUser(token);
		if(user == null){
			return Result.fail("用户效验失败");
		}
		return declareService.insertDeclare(declareDO,user.getId());
	}

	@ApiOperation(value = "修改申报信息",notes = "修改申报信息")
	@ResponseBody
	@PostMapping(value = "/updateDeclare")
	public  Result  updateDeclare(@RequestBody DeclareDO declareDO) {
		return declareService.updateDeclare(declareDO);
	}


	@ResponseBody
	@GetMapping(value = "/verify")
	public  Result  verify(String orgName) {
		return declareService.verify(orgName);
	}


	@ApiOperation(value = "根据登录人id回显申报信息",notes = "根据登录人id回显申报信息",response = DeclareDO.class)
	@ResponseBody
	@GetMapping(value = "/getDeclareByCreaterId")
	public  Result  getDeclareByCreaterId(@RequestHeader(value = TOKEN_TAG, required = false) String token,Long declareReadyId) {
		if(!StringUtil.notEmpty(token)){
			return Result.fail("token效验失败");
		}
		//1.根据token获取用户登录数据
		UserDO user = this.getClientUser(token);
		if(user == null){
			return Result.fail("用户效验失败");
		}
		return declareService.getDeclareByCreaterId(user.getId(),declareReadyId);
	}

	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:declare:add")
	String add(){
	    return "jzweb/declare/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:declare:edit")
	String edit(@PathVariable("id") Long id,Model model){
		DeclareDO declare = declareService.selectById(id);
		model.addAttribute("declare", declare);
	    return "jzweb/declare/edit";
	}
	
	@Log("添加申报主体信息表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:declare:add")
	public Result<String> save( DeclareDO declare){
		declareService.insert(declare);
        return Result.ok();
	}
	
	@Log("修改申报主体信息表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:declare:edit")
	public Result<String>  update( DeclareDO declare){
		boolean update = declareService.updateById(declare);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除申报主体信息表")
	@PostMapping( "/remove")
	@ResponseBody
	public Result<String>  remove( Long id){
		declareService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除申报主体信息表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:declare:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		declareService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
}
